package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-06-12
 * Time: 20:41
 */
//通过这个类,实现后端提供的的接口
    @WebServlet("/blog")
public class BlogServlet extends HttpServlet {
        private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从query string中查询一下看是否有blogId,如果有就是查指定博客,没有就是查所有
        BlogDao blogDao=new BlogDao();
        String blogId=req.getParameter("blogId");
        if(blogId==null){
            List<Blog> blogs=blogDao.selectAll();
            String respString=objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respString);
        }
        else{
            Blog blog=blogDao.selectOne(Integer.parseInt(blogId));

            String respString=objectMapper.writeValueAsString(blog);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(respString);
        }



    }
}
